$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'quoteProduct/quoteproductbaseinfo/list',
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', hidden: true},
            {label: '分类', name: 'categoryName', index: 'category_name', width: 150},
            {label: '分类id', name: 'categoryId', index: 'category_id', hidden: true, width: 150},
            {label: '部件', name: 'partsName', index: 'parts_name', width: 150},
            {label: '部件ID', name: 'partsId', index: 'parts_id', hidden: true, width: 150},
            {label: '创建时间', name: 'createDate', index: 'create_date', width: 100},
            {label: '创建人员', name: 'createUser', index: 'create_user', width: 80},
            {label: '更新时间', name: 'updateDate', index: 'update_date', width: 100},
            {label: '更新人员', name: 'updateUser', index: 'update_user', width: 80}
        ],
        viewrecords: true,
        height: 600,
        rowNum: 20,
        rowList: [20, 30, 50],
        rownumbers: true,
        rownumWidth: 50,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
});

function getCascaderObj(val, opt) {
    return val.map(function (value, index, array) {
        for (var itm of opt) {
            if (itm.value == value) {
                opt = itm.children;
                return itm;
            }
        }
        return null;
    });
}

var vm = new Vue({
    el: '#rrapp',
    data: {
        qParams:{
            categoryName: null,
            partsName: null,
        },
        showList: true,
        loading: null,
        title: null,
        quoteProductBaseInfo: {},
        categoryTree: [], //商品分类树
        categoryIds: [], //多级分类id
        categoryId: null, //分类id
        categoryName: null,
        goodsCategoryDialogVisible: false,// 商品分类树弹窗
        parts: [],//基础部件
        partsId: null,// 部件id
        partsName: null,
        normalAttributeOptionList: [],//普通属性选项
        materialAttributeOptionList: [],//材料属性选项
        materialDefaultOptionList: [],//材料 默认选项列表
        materialDefaultOption: null,//材料 默认选项
        materialDefaultOptionName2List: [],// 克重默认列表
        materialDefaultOptionName2: null,//默认克重
    },
    updated: function () {
        //页面更新后 选中 已存在checkbox
        for (var i = 0; i < vm.normalAttributeOptionList.length; i++) {
            var temp = vm.normalAttributeOptionList[i];
            if (temp.selected === true) {
                this.$refs.normalAttributeOptionTable.toggleRowSelection(temp, true);
            }
        }

        for (var i = 0; i < vm.materialAttributeOptionList.length; i++) {
            var temp = vm.materialAttributeOptionList[i];
            if (temp.selected === true) {
                this.$refs.materialAttributeOptionTable.toggleRowSelection(temp, true);
            }
        }
        if(vm.loading){
            vm.loading.close();
        }
    },
    methods: {
        query: function () {
            vm.reload();
        },

        add: function () {
            vm.title = "新增";
            vm.quoteProductBaseInfo = {};
            vm.getAddInfo();
        },
        update: function (event) {
            var grid = $("#jqGrid");
            var rowId = getSelectedRow();
            var rowData = grid.jqGrid('getRowData', rowId);

            if (rowId == null) {
                return;
            }
            vm.showList = false;

            vm.loading =  this.$loading({
                lock: true,
                text: '努力加载中',
                spinner: 'el-icon-loading',
            });

            vm.title = "修改";
            vm.categoryId = rowData.categoryId;
            vm.categoryName = rowData.categoryName;
            vm.partsId = rowData.partsId;
            vm.partsName = rowData.partsName;
            vm.getUpdateInfo(rowData.categoryId, rowData.partsId);

        },

        getAddInfo: function () {
            // 线获取添加模板基本信息
            $.get(baseURL + "quoteProduct/quoteproductbaseinfo/getCategoryTree", function (r) {
                vm.categoryTree = r.addInfo.categoryTree;
                vm.goodsCategoryDialogVisible = true;
            });

        },
        // 加载编辑所需信息
        getUpdateInfo: function (categoryId, partsId) {
            $.get(baseURL + "quoteProduct/quoteproductbaseinfo/getExistAttributeOption?partsId=" + partsId + "&categoryId=" + categoryId, function (r) {
                vm.normalAttributeOptionList = r.attributeOptionMap.normalAttributeOptionList;
                vm.materialAttributeOptionList = r.attributeOptionMap.materialAttributeOptionData.materialAttributeOptionList;
                vm.materialDefaultOptionName2 = r.attributeOptionMap.materialAttributeOptionData.materialDefaultOptionName2;
                vm.materialDefaultOptionName2List = r.attributeOptionMap.materialAttributeOptionData.materialDefaultOptionName2List;
                vm.materialDefaultOption = r.attributeOptionMap.materialAttributeOptionData.materialDefaultOption;
                vm.materialDefaultOptionList = r.attributeOptionMap.materialAttributeOptionData.materialDefaultOptionList;
            });

        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                page: page,
                postData:vm.qParams,
            }).trigger("reloadGrid");

            this.clearSaveOrUpdateData();
        },
        //分类树变化
        categoryChange: function (value) {
            //取到末级的分类id
            var categoryId = value[value.length - 1];
            vm.categoryId = categoryId;
            // 获取分类名称
            var categoryList = getCascaderObj(value, vm.categoryTree);
            vm.categoryName = categoryList[categoryList.length - 1].label;
            //查询该分类下的部件
            $.get(baseURL + "quoteProduct/quoteproductbaseinfo/getParts?categoryId=" + categoryId, function (r) {
                vm.parts = r.partsList;
            });
        },

        //部件选择改变
        partsChange: function (value) {
            var parts = vm.parts.find(function (option) {
                return option.id === value
            });
            vm.partsName = parts.partsName;
        },

        // 弹窗确定按钮展示属性选线
        showAttribute: function () {
            // 先判断分类是否选择
            if (vm.categoryId == null) {
                this.$message.error('请先选择分类');
                return;
            }
            if (vm.parts.length > 0 && vm.partsId == null) {
                this.$message.error('请选择部件');
                return;
            }
            //查询分类对应属性选项列表
            var self = this;
            $.ajax({
                type: "POST",
                url: baseURL + "quoteProduct/quoteproductbaseinfo/getAttributeOption",
                contentType: "application/json",
                data: JSON.stringify(vm.categoryIds),
                success: function (r) {
                    if (r.code == 0) {
                        vm.normalAttributeOptionList = r.attributeOptionMap.normalAttributeOptionList;
                        vm.materialAttributeOptionList = r.attributeOptionMap.materialAttributeOptionList;
                        vm.goodsCategoryDialogVisible = false;
                        vm.showList = false;
                        vm.loading = self.$loading({
                            lock: true,
                            text: '努力加载中',
                            spinner: 'el-icon-loading',
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },


        // 弹窗关闭
        categoryTreeClose: function () {
            //清空相关内容
            this.clearSaveOrUpdateData();

        },

        //清除保存或者修改 相关
        clearSaveOrUpdateData: function () {
            vm.categoryTree = [];
            vm.categoryId = null;
            vm.categoryIds = [];
            vm.categoryName = null;

            vm.parts = [];
            vm.partsId = null;
            vm.partsName = null;

            vm.goodsCategoryDialogVisible = false;
            vm.close = null;

            vm.normalAttributeOptionList = [];//普通属性选项
            vm.materialAttributeOptionList = [];//材料属性选项
            vm.materialDefaultOptionList = [];//材料 默认选项列表
            vm.materialDefaultOption = null;//材料 默认选项
            vm.materialDefaultOptionName2List = [];// 克重默认列表
            vm.materialDefaultOptionName2 = null;//默认克重
        },

        //普通属性选择变化 赋值给默认属性下拉框
        changeAttributeValue: function (value) {
            var normalSelectedOptionList = value.normalSelectedOptionList;
            var tempList = [];
            for (var i = 0; i < normalSelectedOptionList.length; i++) {
                var optionTemp = value.normalOptionList.find(function (option) {
                    return option.id === normalSelectedOptionList[i];
                })
                tempList.push(optionTemp);
            }
            value.normalSelectedTempOptionList = tempList;
        },

        //材料table选择
        materialSelected: function (selection, row) {
            var tempList = []; //默认选项列表
            for (var i = 0; i < selection.length; i++) {
                var tempObject = {optionName: selection[i].optionName, optionKey: selection[i].optionKey};
                tempList.push(tempObject);

            }
            vm.materialDefaultOptionList = tempList; //赋值默认选项
        },
        //材料默认选项发生变化
        materialDefaultOptionChange: function (value) {
            // 通过optionKey 查找响应的optionName2
            var tempMaterialAttributeOptionList = vm.materialAttributeOptionList.find(function (option) {
                return option.optionKey === value;
            })
            var tempList = [];
            //遍历对应的label
            for (var i = 0; i < tempMaterialAttributeOptionList.materialSelectedOptionList.length; i++) {
                var tempObject = tempMaterialAttributeOptionList.materialOptionList.find(function (option) {
                    return option.id === tempMaterialAttributeOptionList.materialSelectedOptionList[i];
                })
                tempList.push(tempObject);
            }
            vm.materialDefaultOptionName2List = tempList;
            vm.materialDefaultOptionName2 = null;

        },

        //生成商品模板
        generateProductTemplate: function () {
            // 商品分类不能为空
            if (!vm.categoryId) {
                this.$message.error('分类不能为空!');
                return;
            }
            var generateDate = this.handleData();
            if (!generateDate) {
                return;
            }
            // 先处理 普通属性选项
            generateDate.categoryId = vm.categoryId;
            generateDate.partsId = vm.partsId;

            var self = this;
            this.$confirm('确定要生成商品模板吗, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const loading = self.$loading({
                    lock: true,
                    text: '生成模板中,请勿刷新页面',
                    spinner: 'el-icon-loading'
                });
                $.ajax({
                    type: "POST",
                    url: baseURL + "quoteProduct/quoteproductbaseinfo/generateProductTemplate",
                    contentType: "application/json",
                    data: JSON.stringify(generateDate),
                    success: function (r) {
                        loading.close();
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                self.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            }).catch(() => {
                //loading.close();
            });

        },

        updateProductTemplate: function () {
            // 商品分类不能为空
            if (!vm.categoryId) {
                this.$message.error('分类不能为空!');
                return;
            }
            var generateDate = this.handleData();
            if (!generateDate) {
                return;
            }
            // 先处理 普通属性选项
            generateDate.categoryId = vm.categoryId;
            generateDate.partsId = vm.partsId;

            var self = this;
            this.$confirm('确定要更新商品模板吗, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const loading = self.$loading({
                    lock: true,
                    text: '更新模板中,请勿刷新页面',
                    spinner: 'el-icon-loading'
                });
                $.ajax({
                    type: "POST",
                    url: baseURL + "quoteProduct/quoteproductbaseinfo/updateProductTemplate",
                    contentType: "application/json",
                    data: JSON.stringify(generateDate),
                    success: function (r) {
                        loading.close();
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                self.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            }).catch(() => {
                //loading.close();
            });

        },


        handleData: function () {
            var generateDate = {};
            var flag = false;
            var optionFlag = true;

            //获取普通选中属性
            if (this.$refs.normalAttributeOptionTable.selection.length > 0) {
                flag = true;
                var tempList = [];
                for (var i = 0; i < this.$refs.normalAttributeOptionTable.selection.length; i++) {
                    var selection = this.$refs.normalAttributeOptionTable.selection[i];
                    var tempObject = {};
                    tempObject.id = selection.id; //属性id
                    tempObject.attributeName = selection.attributeName;// 属性名称
                    tempObject.normalSelectedOptionList = selection.normalSelectedOptionList // 选中选项
                    if (!selection.normalSelectedOptionList || selection.normalSelectedOptionList.length == 0) {
                        optionFlag = false;
                        this.$message.error('选择行【' + selection.attributeName + "】请选择选项");
                        return;
                    }
                    tempObject.normalDefaultOption = selection.normalDefaultOption;// 默认选项
                    if (!selection.normalDefaultOption) {
                        optionFlag = false;
                        this.$message.error('选择行【' + selection.attributeName + "】请选择默认选项");
                        return;
                    }
                    tempList.push(tempObject);
                }
                generateDate.normalAttributeOptionSelectedList = tempList;
            }

            // 获取材料选中属性
            if (this.$refs.materialAttributeOptionTable.selection.length > 0) {
                var tempList = []; //选中材料列表
                for (var i = 0; i < this.$refs.materialAttributeOptionTable.selection.length; i++) {
                    var selection = this.$refs.materialAttributeOptionTable.selection[i];
                    var tempObject = {};
                    tempObject.id = selection.id; //属性id
                    tempObject.attributeName = selection.attributeName;// 属性名称
                    tempObject.materialSelectedOptionList = selection.materialSelectedOptionList;//选中的材料选项
                    if (!selection.materialSelectedOptionList || selection.materialSelectedOptionList.length == 0) {
                        optionFlag = false;
                        this.$message.error('选择行【' + selection.attributeName + "】请选择选项");
                        return;
                    }
                    tempList.push(tempObject);
                }
                generateDate.materialAttributeOptionSelectedList = tempList;
                if (!vm.materialDefaultOptionName2) {
                    optionFlag = false;
                    this.$message.error('请选择材料默认克重!');
                    return;
                }
                generateDate.materialDefaultOptionName2 = vm.materialDefaultOptionName2;

            }

            if (!flag) {
                this.$message.error('请选择属性选项!');
                return;
            }

            if (!optionFlag) {//数据校验
                return;
            }

            return generateDate;
        }
    }
});